package off_trial

import (
	sqlc "bp/db/sqlc"
	"bp/internal/render"
	"bp/internal/service/com/offer"
	"bp/internal/util"
	offTrialGrpc "bp/rpc/gen/mwebapi/off_trial"
	"context"
)

func (s *OffTrialMWebApiImp) DoTrial(ctx context.Context, req *offTrialGrpc.DoTrialReq) (res *offTrialGrpc.DoTrialRes, err error) {
	slog := util.NewContextLogger(ctx, s.slog)
	slog.Infof("offer_trial_imp/query.DoTrial=>%+v", req)
	defer render.FriendlyEntityError(&err, EntityName)
	res = &offTrialGrpc.DoTrialRes{}

	var off int32
	var trialedOwnerPtrs []*offer.TrialedOwner
	var trialedOfferItemPtrOfCardDiscount *offer.TrialedOfferItem
	err = s.dao.NewTxRunner().SqlcExecTx(ctx, func(q *sqlc.Queries) (err error) {
		toTrialOwnerPtrs, err := s.VldDoTrialReq(ctx, q, req)
		if err != nil {
			return
		}
		off, trialedOwnerPtrs, trialedOfferItemPtrOfCardDiscount, err = s.comHub.OfferService.DoTrial(ctx, q, &offer.DoTrialParam{
			OutTransNo:  req.OutTransNo,
			TrialScene:  req.TrialScene,
			TrialIssuer: req.TrialIssuer,
			OutCardID:   req.OutCardId,
			OwnerPtrs:   toTrialOwnerPtrs,
		})
		if err != nil {
			return
		}
		slog.Infof("优惠试算 ok")
		return
	})
	if err != nil {
		return
	}

	res.Off = off
	res.Owners = s.ConvOffTrialOwnerPtrArrayEntityToPb()(trialedOwnerPtrs)
	res.CardDiscount = s.ConvOffTrialOfferItemPtrEntityToPb()(trialedOfferItemPtrOfCardDiscount)
	return
}
